<template>
  <div>
    <Layouts :gutter="24" :span="[4, 20]" :color="['', '#F0F2F5']">
      <template #left>
        <div class="patient-header tagsSelect">
          <!-- <div class="patient-title">患者</div>
          <div class="patient-line"></div> -->
          <div class="sidebar-tabs">
            <span
              class="tab-btn"
              :class="{ active: types === item.perms }"
              @click="parentMethod(item.perms)"
              v-for="(item, index) in menuItem"
            >
              {{ item.menuName }}</span
            >
          </div>
          <div>
            <el-button
              type="primary"
              v-btnPermission="'btn-patient-add'"
              @click="onPatientAdd"
              >建档</el-button
            >
          </div>
        </div>
        <div class="patient-container" v-if="types != null">
          <div class="search-container">
            <el-input
              v-model="patientName"
              placeholder="搜索姓名/电话/身份证号/诊号"
              class="search-input"
              clearable
              @input="handleSearch"
              @clear="handleSearch"
            >
            </el-input>

            <!-- <el-select
              v-model="selectedDate"
              placeholder="选择日期"
              class="date-select"
              @change="handleSearch"
              :suffix-icon="CaretBottom"
            >
              <el-option label="今天" value="today" />
              <el-option label="昨天" value="yesterday" />
              <el-option label="明天" value="tomorrow" />
            </el-select> -->
            <!-- <div
              @click="CustomDatePickerShow = !CustomDatePickerShow"
              class="register-date-box"
            >
              {{ formattedVisitDate }}
              <el-icon size="14"><CaretBottom /></el-icon>
            </div>
            <div
              class="register-date-custom-picker"
              v-if="CustomDatePickerShow"
            >
              <DatePickerTime
                @change="CustomDatePickerChange"
                @update:modelValue="CustomDatePickerChange"
                :time="visitDate"
              ></DatePickerTime>
            </div> -->
          </div>
          <div v-if="patientList.length > 0">
            <div
              class="user-info"
              v-for="(patient, index) in patientList"
              :key="index"
              @click="onUserInfo(patient.patientId)"
              :class="patientId === patient.patientId ? 'user-info-active' : ''"
            >
              <div style="display: flex; align-items: center">
                <img
                  src="@/assets/pharmacy/man.png"
                  alt=""
                  class="patient-icon"
                  v-if="patient.patientGender == '1'"
                />
                <img
                  src="@/assets/pharmacy/woman.png"
                  alt=""
                  class="patient-icon"
                  v-else-if="patient.patientGender == '2'"
                />

                <img
                  src="@/assets/pharmacy/icon_weizhi_nor.png"
                  class="patient-icon"
                  v-if="patient.patientGender == '3'"
                />

                <span
                  class="name"
                  :title="patient.patientName"
                  style="
                    margin-left: 5px;
                    max-width: 87px;
                    display: -webkit-box;
                    -webkit-line-clamp: 1;
                    -webkit-box-orient: vertical;
                    overflow: hidden;
                    text-overflow: ellipsis;
                  "
                  >{{ patient.patientName }}</span
                >
                <img
                  src="@/assets/patient/icon_vip_nor.svg"
                  v-if="patient.isMember == '1'"
                />
              </div>
              <div
                style="
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                  width: 117px;
                "
              >
                <span class="phone-number">{{ patient.patientPhone }}</span>
                <span class="age">{{ patient.ageYear }}岁</span>
              </div>
            </div>
          </div>
          <div v-else>
            <el-empty
              :image-size="100"
              :image="emptyImage"
              description="暂无数据"
            />
          </div>
        </div>
        <div v-else>
          <el-empty
            :image-size="100"
            :image="emptyImage"
            description="暂无权限"
          />
        </div>
      </template>
      <template #right v-if="types != null">
        <div style="display: flex; justify-content: space-between">
          <patient-user :patientDetail="patientDetail" @edit="editPatient" />
          <member-card
            :patientId="patientId"
            :patientDetail="patientDetail"
            @recharge="refulshPatientList"
          />
        </div>
        <div>
          <record :patientId="patientId" :selectedDate="selectedDate" />
        </div>
      </template>
      <template #right v-else>
        <el-empty
          :image-size="260"
          :image="emptyImage"
          style="padding-top: 100px"
          description="暂无权限"
        />
      </template>
    </Layouts>
    <patientUpdata
      ref="patientUpdataRef"
      @refresh="refulshPatientList"
      :addType="addType"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { CaretBottom } from '@element-plus/icons-vue';
import PatientUser from './common/patientUser.vue';
import MemberCard from './common/memberCard.vue';
import patientUpdata from './common/patientUpdata.vue';
import record from './common/record.vue';
import stores from '@/store';
import emptyImage from '@/assets/icon/internet_empty_illustration.svg';
import {
  getPatientList,
  getPatientDetail,
  getPatientMedicalField,
} from '@/api/patient';
import type {
  PatientInfo,
  PatientDetail,
  RechargeOrderListData,
  RechargeOrderQueryParams,
} from '@/types/patient';
const patientUpdataRef = ref<InstanceType<typeof patientUpdata>>();
const patientList = ref<PatientInfo[]>([]); // 患者列表
import dayjs from 'dayjs';
// 搜索和筛选
const patientName = ref('');
const selectedDate = ref('today');
const patientDetail = ref<PatientDetail | undefined>(undefined); // 当前选中的患者详情
const pageNo = ref(1);
const pageSize = ref(10);
const CustomDatePickerShow = ref(false);
const visitDate = ref(''); // 选择的就诊日期
const route = useRoute();
const patientId = ref<number | null>(null); // 当前选中的患者ID
const handleClick = (tab: any, event: Event) => {
  //console.log(tab, event);
};
const addType = ref('1'); // '1'表示添加新患者，'2'表示编辑患者
const onUserInfo = async (id: any) => {
  // 这里可以添加跳转到患者详情页面的逻辑
  patientId.value = id; // 设置当前选中的患者ID
  // 获取患者详情
  const data = await getPatientDetail({ patientId: id });
  if (data.code != '200') {
    return;
  }
  patientDetail.value = data.data; // 更新患者详情
};
async function refreshPatientList() {
  try {
    const data = {
      patientName: patientName.value,
      pageNo: 1,
      pageSize: 1000000,
    };
    const response = await getPatientList(data);
    if (response && response.data) {
      patientList.value = response.data;
      if (patientList.value.length > 0) {
        if (patientId.value == null) {
          patientId.value = patientList?.value[0]?.patientId || null; // 默认选中第一个患者
        }
        // patientId.value = patientList?.value[0]?.patientId || null; // 默认选中第一个患者
        onUserInfo(patientId.value);
      } else {
        patientId.value = null;
        patientDetail.value = undefined;
      }
    }
    //console.log('患者列表:', response);
  } catch (error) {
    //console.error('获取患者列表失败:', error);
  }
}

let menuList = ref<any>(
  await stores.useBaseDataStore().findMenuList(route.query.menuId)
);

const types = ref<string>(); // 默认选中标签
let menuItem = ref<any>(
  menuList.value.filter((item: any) => item.menuType == 2)
);
//console.log(menuList, 'menuList');

if (menuItem.value.length > 0) {
  types.value = menuItem.value[0].perms; // 默认选中标签
}

const parentMethod = (e: string) => {
  types.value = e;
};
const refulshPatientList = () => {
  if (addType.value == '2') {
    onUserInfo(patientId.value);
    refreshPatientList();
  } else {
    refreshPatientList();
  }
};
onMounted(() => {
  // 获取患者列表
  visitDate.value = dayjs().format('YYYY-MM-DD');
  refreshPatientList();
});
// 监听搜索变化
const handleSearch = () => {
  //console.log('搜索关键词:', patientName.value);
  //console.log('选择日期:', selectedDate.value);
  refreshPatientList();
  // 这里可以添加搜索逻辑
};
const formattedVisitDate = computed(() => {
  const val = visitDate.value;
  if (!val) return '';
  const current = dayjs();
  const target = dayjs(val);
  if (!target.isValid()) return '';
  return target.isSame(current, 'day') ? '今天' : target.format('MM-DD');
});
const CustomDatePickerChange = (date: any) => {
  // 为空直接关闭
  if (!date) {
    CustomDatePickerShow.value = false;
    return;
  }

  // 规范化为 YYYY-MM-DD 字符串
  const next = dayjs(date).isValid()
    ? dayjs(date).format('YYYY-MM-DD')
    : String(date);
  visitDate.value = next;
  patientId.value = null;
  // dispenseDetail.value = undefined;
  CustomDatePickerShow.value = false;
  refreshPatientList();
};
const onPatientAdd = () => {
  //console.log('添加新患者');
  patientUpdataRef.value?.open(); // 打开添加患者弹窗并传递回调
  addType.value = '1';
};
const editPatient = async () => {
  patientUpdataRef.value?.open1(patientDetail.value);
  addType.value = '2';
};
</script>

<style scoped lang="scss">
.sidebar-tabs {
  flex-shrink: 0;
  display: flex;
  gap: 24px;
  height: 52px;
  padding-left: 12px;
  .tab-btn {
    cursor: pointer;
    font-weight: 400;
    font-size: 18px;
    color: rgba(0, 0, 0, 0.4);
    line-height: 52px;
    text-align: left;
    font-style: normal;
    text-transform: none;
    position: relative;

    &.active {
      font-weight: 400;
      font-size: 18px;

      color: #18b3ab;
      text-align: left;
      font-style: normal;
      text-transform: none;
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 3px;
        background: #18b3ab;
      }
    }
  }
}
.patient-container {
  padding: 10px;
  height: calc(100% - 55px);
  overflow: auto;
  .search-container {
    display: flex;
    gap: 6px;
    align-items: center;
    margin-bottom: 10px;
    position: relative;
    .search-input {
      flex: 1;
      width: 182px;
    }
    .date-select {
      width: 48px;
    }
  }
}

.patient-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  width: 100%;
  padding: 0px 10px;
  border-bottom: 1px solid #e7e7e7;

  .patient-title {
    font-size: 18px;
    font-weight: 600;
    color: var(--el-color-primary);
  }

  .patient-line {
    position: absolute;
    width: 30px;
    top: 45px;
    height: 2px;
    background-color: var(--el-color-primary);
    margin-top: 4px;
  }
}
.user-info-container {
  background-color: #f0f0f0;
  padding: 10px 3px;
}
.user-info-active {
  background: rgba(24, 179, 171, 0.1);
  border-radius: 6px 6px 6px 6px;
  border: 1px solid var(--el-color-primary);
}
.user-info {
  display: flex;
  align-items: center;
  padding: 10px;
  margin-bottom: 5px;
  justify-content: space-between;
  border-radius: 5px;
  cursor: pointer;
  .user-info.selected {
    background-color: #bce8f1;
  }

  .avatar {
    width: 20px;
    height: 20px;
  }

  .name {
    // font-weight: bold;
  }

  .dropdown-icon {
    margin-left: auto;
  }

  .phone-number {
    font-family: Microsoft YaHei, Microsoft YaHei;
    font-weight: 400;
    font-size: 13px;
    color: rgba(0, 0, 0, 0.4);
    text-align: left;
    font-style: normal;
    text-transform: none;
  }

  .age {
    margin-left: auto;
    font-family: Microsoft YaHei, Microsoft YaHei;
    font-weight: 400;
    font-size: 13px;
    color: rgba(0, 0, 0, 0.4);
  }
}
.register-date-box {
  cursor: pointer;
  text-align: right;
}
.register-date-custom-picker {
  position: absolute;
  top: 100%;
  left: 0;
  z-index: 2000;
  margin-top: 4px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 8px 8px 4px;
  width: 100%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
}
</style>
<style lang="scss">
.date-select {
  .el-select__wrapper {
    border: none !important;
    box-shadow: none !important;
    background-color: transparent !important;
    padding: 0 !important;
  }

  .el-input__inner {
    color: var(--el-color-primary) !important;
    font-weight: 500 !important;
  }

  // 设置后缀图标颜色为黑色
  .el-icon {
    color: #000 !important;
  }
}
.patient-icon {
  width: 16px;
  height: 16px;
  font-size: 16px;
}
</style>
